package com.beiye.drivertransport.SubActivity;

import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.beiye.drivertransport.R;
import com.beiye.drivertransport.bean.CompareFaceBean;
import com.beiye.drivertransport.bean.WriterBean;
import com.beiye.drivertransport.config.AppInterfaceConfig;
import com.beiye.drivertransport.thirdparty.oss.OSSUpFileListener;
import com.beiye.drivertransport.utils.CustomProgressDialog;
import com.beiye.drivertransport.utils.HelpUtil;
import com.beiye.drivertransport.utils.LogUtils;
import com.beiye.drivertransport.utils.MessageEvent;
import com.beiye.drivertransport.utils.ToastUtil;
import com.beiye.drivertransport.view.LinePathView;
import com.githang.statusbar.StatusBarCompat;
import com.squareup.picasso.Picasso;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.File;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import okhttp3.Call;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

//专项学习签名
public class SignSpeciedlearningActivity extends AppCompatActivity implements View.OnClickListener{
    private Integer sn;
    final File fileDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
            "Signname");
    private static final int REQUEST_EXTERNAL_STORAGE = 1;
    private static String[] PERMISSIONS_STORAGE = {
            "android.permission.READ_EXTERNAL_STORAGE",
            "android.permission.WRITE_EXTERNAL_STORAGE" };
    private CustomProgressDialog dialog;
    private LinePathView signatureview;
    private TextView img_sign;
    private ImageView img_sign2;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sign_speciedlearning);

        initData();
        ImageView back =(ImageView) findViewById(R.id.img_back1);
        //签名
        img_sign = (TextView) findViewById(R.id.img_sign1);
        TextView clear =(TextView) findViewById(R.id.tv_clear);
        TextView sure =(TextView) findViewById(R.id.tv_sure);
        signatureview = (LinePathView) findViewById(R.id.signatureview);

        back.setOnClickListener(this);
        clear.setOnClickListener(this);
        sure.setOnClickListener(this);
        img_sign.setOnClickListener(this);
    }
    @Override
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.img_back1) {
            finish();
        } else if (id == R.id.tv_clear) {//重新签名
            img_sign2.setVisibility(View.GONE);
            img_sign.setVisibility(View.GONE);
            signatureview.clear();
        } else if (id == R.id.img_sign1) {//签名
            img_sign.setVisibility(View.GONE);
        } else if (id == R.id.tv_sure) {//保存签名

            try {
                //检测是否有写的权限
                int permission = ActivityCompat.checkSelfPermission(SignSpeciedlearningActivity.this,
                        "android.permission.WRITE_EXTERNAL_STORAGE");
                if (permission != PackageManager.PERMISSION_GRANTED) {
                    ToastUtil.showShortToast(SignSpeciedlearningActivity.this, "请到手机设置界面里找驾运宝允许开启读写手机存储,否则不能点确定");

                    return;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            save(fileDir);
        }
    }

    public void initData() {
        StatusBarCompat.setStatusBarColor(this, Color.parseColor("#1F80C4"));
        verifyStoragePermissions(this);
        Bundle bundle = getIntent().getExtras();
        sn = bundle.getInt("sn");
        String signPicUrl = bundle.getString("signPicUrl");
        img_sign2 = (ImageView) findViewById(R.id.img_sign2);
        if(signPicUrl.equals(""))
        {
            img_sign2.setVisibility(View.GONE);

        }else{
            img_sign2.setVisibility(View.VISIBLE);
            Picasso.with(SignSpeciedlearningActivity.this).load(Uri.parse(signPicUrl)).placeholder(R.mipmap.no_data1).into(img_sign2);//加载图片

        }
    }

    /**
     *  保存图片
     */
    private void save(File fileDir) {
        if (!fileDir.exists()) {
            fileDir.mkdirs();
        }
        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyyMMddHHmmss");
        final String fileName = simpleDateFormat.format(new Date())+".png";
        File savefile = new File(fileDir , fileName);
        final String filePath = getFilePath(fileDir);
        if (signatureview.getTouched()){//是否签名

            try {
                signatureview.save(filePath);
            } catch (IOException e) {
                e.printStackTrace();
            }
            LogUtils.e("测试", "SignSpeciedlearningActivitysave: "+savefile.length() );
            //uploadImg(savefile);//上传服务器封装方法
            uploadFile(SignSpeciedlearningActivity.this,savefile,5);
            //  Toast.makeText(SignActivity.this,"上传成功",Toast.LENGTH_LONG).show();
        }else{
            Toast.makeText(SignSpeciedlearningActivity.this, "签名不能为空", Toast.LENGTH_SHORT).show();
        }
    }


    /*private static final MediaType MEDIA_TYPE_PNG = MediaType.parse("image/png");
    private final OkHttpClient client = new OkHttpClient();
    private void uploadImg(File mediaFile) {
        // mImgUrls为存放图片的url集合
        MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);

        if (mediaFile != null) {
            builder.addFormDataPart("signImg", mediaFile.getName(), RequestBody.create(MEDIA_TYPE_PNG, mediaFile));
            builder.addFormDataPart("sn",sn.toString());
        }
        MultipartBody requestBody = builder.build();
        //showLoadingDialog("正在加载");
        dialog = CustomProgressDialog.show(SignSpeciedlearningActivity.this, "保存中...", true, null);
        //构建请求
        Request request = new Request.Builder()
                .url(AppInterfaceConfig.BASE_URL + "app/spec/uploadSignForT")//地址
                .post(requestBody)//添加请求体
                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                LogUtils.e("上传失败", e.getLocalizedMessage());
                dialog.dismiss();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String str = response.body().string();
                LogUtils.e("上传成功", str);
                dialog.dismiss();
                finish();


            }
        });

    }*/

    /**
     *   得到图片的路径 以及图片的名字
     */
    private String getFilePath(File fileDir) {
        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyyMMddHHmmss");
        final String fileName = simpleDateFormat.format(new Date())+".png";
        LogUtils.e("filename","---"+fileName);
        File file = new File(fileDir,fileName);
        return file.getAbsolutePath();
    }


    public  void verifyStoragePermissions(Activity activity) {

        try {
            //检测是否有写的权限
            int permission = ActivityCompat.checkSelfPermission(activity,
                    "android.permission.WRITE_EXTERNAL_STORAGE");
            if (permission != PackageManager.PERMISSION_GRANTED) {
                // 没有写的权限，去申请写的权限，会弹出对话框
                ActivityCompat.requestPermissions(activity, PERMISSIONS_STORAGE,REQUEST_EXTERNAL_STORAGE);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public void uploadFile(Context context, File faceImgFile, int type) {
        HelpUtil.uploadFile(context, faceImgFile, type, new OSSUpFileListener() {

            @Override
            public void onSuccess(WriterBean bean) {
                String oosUrl=bean.getData().getObjectAcsUrl();
                finishChSign(oosUrl);
                dialog.dismiss();
            }

            @Override
            public void onFail(String msg, WriterBean bean) {
                dialog.dismiss();
            }

        });
    }

    public void finishChSign(String url){
        JSONObject js_request = new JSONObject();//服务器需要传参的json对象
        try {
            js_request.put("sn", sn.toString());//根据实际需求添加相应键值对
            js_request.put("signPicUrl", url);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        RequestParams params = new RequestParams(AppInterfaceConfig.BASE_URL + "course/userStcHour/finishChSign");
        params.setAsJsonContent(true);
        params.setBodyContent(js_request.toString());
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                LogUtils.e("测试", "onSuccess: "+result);
                finish();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                LogUtils.e("测试", "onError: " );
            }

            @Override
            public void onCancelled(CancelledException cex) {
                LogUtils.e("测试", "onCancelled: " );
            }

            @Override
            public void onFinished() {
                LogUtils.e("测试", "onFinished: " );
            }
        });
    }
}
